"""
数据库模型
"""
from sqlalchemy import Column, Integer, String, Enum, DateTime, Boolean, Integer
from sqlalchemy.sql import func
from app.models.base import Base
from typing import Optional

class Database(Base):
    """数据库表模型"""
    __tablename__ = 't_databases'
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment='数据库ID')
    name = Column(String(100), nullable=False, comment='数据库名称')
    host = Column(String(255), nullable=False, comment='主机地址')
    port = Column(Integer, nullable=True, comment='端口')
    type = Column(String(50), nullable=True, comment='数据库类型(MySQL/PostgreSQL/Redis等)')
    status = Column(Enum('running', 'stopped', 'error', 'normal', 'warning'), nullable=False, default='normal', comment='状态')
    connections = Column(Integer, nullable=True, comment='当前连接数')
    max_connections = Column(Integer, nullable=True, comment='最大连接数')
    size = Column(String(50), nullable=True, comment='数据库大小')
    qps = Column(Integer, nullable=True, comment='QPS(每秒查询数)')
    uptime = Column(String(50), nullable=True, comment='运行时长')
    is_deleted = Column(Boolean, nullable=False, default=False, comment='是否删除: 0-否, 1-是')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, nullable=False, default=func.now(), onupdate=func.now(), comment='更新时间')
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'host': self.host,
            'port': self.port,
            'type': self.type,
            'status': self.status,
            'connections': self.connections,
            'max_connections': self.max_connections,
            'size': self.size,
            'qps': self.qps,
            'uptime': self.uptime,
            'is_deleted': self.is_deleted,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
